package com.zhilun;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boer.DeviceTyreLocationSensorParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.*;

@Slf4j
public class ZhiLunCarrierCurrentData {

    //pro
//    public static final String key ="abc75a7e718a48d29cabe2884dae1d44";
//    public static final String secret ="ODY2YmUzZWIwN2Y2ODU0MzIxMGY1NWFkOGQyY2YyMDY=";

    //test
    public static final String key ="ade0ccb442c945fb939a2f82193f6cdf";
    public static final String secret ="MDEwMzE1MjY2MDVjMWUxOTAxNWM2N2I2OGZiYjJiYzc=";

    //pro
//    public static final String url = "https://open.zhilunkeji.com";

    // 构造URL test
    public static final String url = "https://open-p.zhilunkeji.com";
    public static final String api ="/open/api/carrier/currentData";

    static Map<String, Integer> reverseTranslationLocation = new HashMap<>();

    static {
        reverseTranslationLocation.put("L0102", 1);
        reverseTranslationLocation.put("L0101", 2);
        reverseTranslationLocation.put("R0101", 3);
        reverseTranslationLocation.put("R0102", 4);
        reverseTranslationLocation.put("L0202", 5);
        reverseTranslationLocation.put("L0201", 6);
        reverseTranslationLocation.put("R0201", 7);
        reverseTranslationLocation.put("R0202", 8);
        reverseTranslationLocation.put("L0302", 9);
        reverseTranslationLocation.put("L0301", 10);
        reverseTranslationLocation.put("R0301", 11);
        reverseTranslationLocation.put("R0302", 12);
        reverseTranslationLocation.put("L0003", 97);
        reverseTranslationLocation.put("L0001", 98);
        reverseTranslationLocation.put("L0002", 99);
    }


    /**
     * key:ade0ccb442c945fb939a2f82193f6cdf
     * secret:MDEwMzE1MjY2MDVjMWUxOTAxNWM2N2I2OGZiYjJiYzc=
     * @param args
     */
    public static void main(String[] args) {


        // 请求参数
       // String carrierNo = "皖MT530挂";
        String carrierNo = "皖CEE58挂";




        // 构造签名
        Map<String, String[]> paramMap = new HashMap<>();
        paramMap.put("accessKey", new String[] {key});
        paramMap.put("carrierNo",new String[] {carrierNo} );
//        paramMap.put("pageSize", new String[] {pageSize});
       // paramMap.put("alarm", alarm);
   //     paramMap.put("timestamp", new String[] {System.currentTimeMillis() +""});
        String sign = signParameterMap(paramMap, secret);
        System.out.println("sign: " +sign);

        paramMap.put("sign", new String[]{sign});

//        // 构造参数Map
//        Map<String, Object> param = new HashMap<>();
//        param.put("accessKey", key);
//        param.put("currentPage", currentPage);
//        param.put("pageSize", pageSize);
//        param.put("alarm", alarm);
//        param.put("timestamp", timestamp);
//        param.put("sign", sign);


        // 手动拼接URL和参数
        String fullUrl = url +api + "?" +sign;

        // 打印拼接后的URL
        System.out.println("Full URL: " + fullUrl);

        // 使用Hutool发送GET请求
        HttpRequest request = HttpUtil.createGet(fullUrl);

        // 执行请求并获取响应
        HttpResponse response = request.execute();

        // 获取响应结果
        String result = response.body();
        ZhiLunResponse<ZhiLunCarrierInfoDetailResult> testResult = JSON.parseObject(
                result,
                new com.alibaba.fastjson.TypeReference<ZhiLunResponse<ZhiLunCarrierInfoDetailResult>>() {}
        );
        List<DeviceTyreLocationSensorParam> deviceTyreLocationSensorParams = convertToTyreLocationSensorParams(testResult, reverseTranslationLocation);
        System.out.println(JSON.toJSONString(deviceTyreLocationSensorParams, true) );
        System.out.println("Response: " );

        // 将字符串转换为 JSON 对象
        JSONObject jsonObject = JSON.parseObject(result);

        // 格式化输出 JSON 字符串
        String prettyJson = JSON.toJSONString(jsonObject, true);

        // 打印格式化后的 JSON 字符串
        System.out.println(prettyJson);

    }


    public static List<DeviceTyreLocationSensorParam> convertToTyreLocationSensorParams(
            ZhiLunResponse<ZhiLunCarrierInfoDetailResult> testResult, Map<String, Integer> positionMapping) {

        List<DeviceTyreLocationSensorParam> tyreLocationSensorParams = new ArrayList<>();

        // 获取 carrierWheelVOS 列表
        List<ZhiLunCarrierInfoDetailResult.CarrierWheelVO> carrierWheelVOS = testResult.getData().getCarrierWheelVOS();

        for (ZhiLunCarrierInfoDetailResult.CarrierWheelVO carrierWheel : carrierWheelVOS) {
            DeviceTyreLocationSensorParam param = new DeviceTyreLocationSensorParam();

            // 根据 position 映射到 tyreLocationId
            String position = carrierWheel.getPosition();
            if (positionMapping.containsKey(position)) {
                param.setTyreLocationId(positionMapping.get(position));
            }



            // 获取传感器列表
            List<ZhiLunCarrierInfoDetailResult.SensorVO> sensorVOS = carrierWheel.getSensorVOS();
            if (sensorVOS != null && !sensorVOS.isEmpty()) {
                // 假设每个轮位只取第一个传感器
                ZhiLunCarrierInfoDetailResult.SensorVO sensor = sensorVOS.get(0);
                param.setSensorId(sensor.getSensorNo());
            }


            // 将参数对象添加到列表
            tyreLocationSensorParams.add(param);
        }

        return tyreLocationSensorParams;
    }



    public static String signParameterMap(Map<String, String[]> parametersMap, String secret) {
        //添加时间戳，排序并删除空值
        Map<String, String[]> unlock = new HashMap<>(parametersMap);
        unlock.put("timestamp", new String[]{String.valueOf(System.currentTimeMillis() / 1000)});
        List<String> keys = new ArrayList<>(unlock.keySet());
        Collections.sort(keys);
        StringBuilder signStr = new StringBuilder();
        for (String key : keys) {
            String[] values = unlock.get(key);
            if (values.length < 1) {
                continue;
            }
            for (String v : values) {
                signStr.append(key).append("=").append(v).append("&");
            }
        }
        signStr.deleteCharAt(signStr.lastIndexOf("&"));
        String sign = DigestUtils.md5Hex(signStr.toString() + secret);
        signStr.append("&sign=").append(sign);
        return signStr.toString();
    }





}
